<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mobile Demo</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        padding: 20px;
      }

      h1 {
        color: #333;
      }

      p {
        line-height: 1.5;
      }
    </style>
  </head>

  <body>
    <input type="file" id="fileInput" onclick="clearProgress()" />
    <button onclick="uploadFile()">Upload</button>
    <h1 id="progressBar"></h1>
    <script>
      function clearProgress() {
        // 清空进度条
        document.getElementById("progressBar").innerHTML = "";
      }
      function uploadFile() {
        const fileInput = document.getElementById("fileInput");
        const file = fileInput.files[0];
        if (!file) return;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/upload", true);
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
        xhr.setRequestHeader("X-File-Size", file.size);

        // 获取已上传的字节数
        const resumePosition = getResumePosition(encodeURIComponent(file.name));
        xhr.setRequestHeader("X-Start-Byte", resumePosition);

        xhr.upload.onprogress = function (e) {
          if (e.lengthComputable) {
            const percentComplete =
              ((e.loaded + resumePosition) / file.size) * 100;
            console.log(`Progress: ${percentComplete.toFixed(2)}%`);
            document.getElementById(
              "progressBar"
            ).innerHTML = `Progress: ${percentComplete.toFixed(2)}%`;
          }
        };

        xhr.send(file.slice(resumePosition));
      }

      function getResumePosition(fileName) {
        // 这里可以通过发送请求到服务器查询已上传的字节数
        const xhr = new XMLHttpRequest();
        xhr.open("GET", `/progress/${fileName}`, false);
        xhr.send();
        if (xhr.status === 200) {
          return parseInt(xhr.responseText);
        }
        return 0;
      }
    </script>
  </body>
</html>
